<?php
declare(strict_types=1);

namespace app\model;

use think\Model;

class User extends Model
{
    protected $autoWriteTimestamp = true;

    // 关联订单
    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    // 关联领券订单
    public function couponOrders()
    {
        return $this->hasMany(CouponOrder::class);
    }

    // 关联地址
    public function addresses()
    {
        return $this->hasMany(UserAddress::class);
    }

    // 关联会员套餐
    public function packages()
    {
        return $this->hasMany(UserPackage::class);
    }

    // 关联余额流水
    public function balanceFlows()
    {
        return $this->hasMany(UserBalanceFlow::class);
    }

    // 关联支付记录
    public function paymentRecords()
    {
        return $this->hasMany(UserPaymentRecord::class);
    }

    // 关联提现记录
    public function withdrawRecords()
    {
        return $this->hasMany(UserWithdrawRecord::class);
    }

    // 关联推荐人
    public function parent()
    {
        return $this->belongsTo(User::class, 'parent_id');
    }

    // 关联下级用户
    public function children()
    {
        return $this->hasMany(User::class, 'parent_id');
    }

    // 获取当前有效会员套餐
    public function getActivePackage()
    {
        return $this->packages()
            ->where('valid_time', '>', time())
            ->order('id', 'desc')
            ->find();
    }

    // 检查是否是会员
    public function isVip(): bool
    {
        return (bool)$this->getActivePackage();
    }

    // 获取用户折扣率
    public function getDiscountRate(): float
    {
        $package = $this->getActivePackage();
        return $package ? $package->discount_rate : 100;
    }
} 